<script lang="ts" setup>
import XtInlinForm from '@/components/inlinForm/XtInlinForm.vue';
import xtTable from '@/components/table/XtTable.vue';
// import xtDialog from '@/components/xtDialog/XtDialog.vue';
import xtForm from '@/components/form/XtForm.vue';
import { computed, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const appTypeOptions = ref([]);
const pageDictOption = reactive({
  serveObject: [],
  categoryList: [],
  customField: [],
});

const inlineForm = ref<any>({
  labelWidth: '100px',
  items: [
    {
      type: 'input',
      prop: 'serviceItemName',
      label: '事项名称',
    },
    {
      type: 'select',
      prop: 'serviceObject',
      label: '服务对象',
      option: computed(() => pageDictOption.serveObject),
    },
    {
      type: 'select',
      prop: 'responsibleDepartment',
      label: '责任部门',
      option: appTypeOptions,
    },
    {
      type: 'input',
      prop: 'serviceTopic',
      label: '服务主题',
    },
    {
      type: 'select',
      prop: 'associationService',
      label: '关联服务',
      option: [
        { value: '0', label: '是' },
        { value: '1', label: '否' },
      ],
    },
    {
      type: 'select',
      label: '事项状态',
      prop: 'startStopStatus',
      option: [
        { label: '启用', value: '0' },
        { label: '停用', value: '1' },
      ],
    },
  ],
  bars: {
    options: [
      {
        type: 'primary',
        label: '查询',
        types: 'search',
      },
      { type: '', label: '重置', types: 'reset' },
    ],
  },
  formData: {},
});

const tableData = ref<any>({
  Loading: false,
  topBtn: [
    {
      label: '新建服务事项',
      icon: 'Plus',
      type: 'primary',
      name: 'accessApp',
    },
  ],
  columns: [
    { label: '服务事项名称', prop: 'serviceItemName' },
    {
      label: '服务对象',
      prop: 'serviceObject',
      formatter: (row) => {
        const option = pageDictOption.serveObject.find(
          (item) => item.value === row.serviceObject
        );
        return option ? option.label : row.serviceObject;
      },
    },
    {
      label: '责任部门',
      prop: 'responsibleDepartment',
      formatter: (row) => {
        const option = appTypeOptions.value.find(
          (item) => item.value === row.responsibleDepartment
        );
        return option ? option.label : row.responsibleDepartment;
      },
      align: 'center',
    },
    { label: '服务主题', prop: 'serviceTopic' },
    {
      label: '关联服务',
      prop: 'associationService',
      formatter: (row) => {
        return row.associationService === '0' ? '是' : '否';
      },
      align: 'center',
    }, //0开启 1关闭
    { label: '启停状态', prop: 'startStopStatus', type: 'startStopType' }, //0启用 1关闭
    { label: '最近修改时间', prop: 'updateDate' },
    { label: '图标', prop: 'icon', type: 'img' },
    { label: '操作', prop: 'operation', type: 'operate', minWidth: 120 },
  ],
  data: [],
  pagination: {
    total: 0,
    pageSize: 10,
    pageNumber: 1,
  },
});

const dialogRef = ref<any>(null);
const dialogRefForm = ref<any>(null);
const dialogOption = reactive({
  title: '服务事项',
  formData: { icon: '' },
  formOption: {
    item: [
      {
        label: '服务事项名称',
        span: 12,
        type: 'mixed',
        options: [
          { label: '选项1', prop: 'option1' },
          { label: '选项2', prop: 'option2' },
          { label: '选项3', prop: 'option3', disabled: true },
          { label: '选项4', prop: 'option4' },
        ],
      },
      {
        label: '服务对象',
        prop: 'serviceObject',
        type: 'select',
        option: computed(() => pageDictOption.serveObject),
        span: 12,
        formatter: (row) => {
          const option = pageDictOption.serveObject.find(
            (item) => item.value === row
          );
          return option ? option.label : row;
        },
      },
      {
        label: '责任部门',
        prop: 'responsibleDepartment',
        type: 'select',
        span: 12,
        option: appTypeOptions,
        formatter: (row) => {
          const option = appTypeOptions.value.find(
            (item) => item.value === row
          );
          return option ? option.label : row;
        },
      },
      { label: '服务主题', prop: 'serviceTopic', span: 12, type: 'input' },
      {
        label: '关联服务',
        prop: 'associationService',
        type: 'radio',
        option: [
          { value: '0', label: '是' },
          { value: '1', label: '否' },
        ],
        span: 12,
        formatter: (row) => {
          return row === '0' ? '是' : '否';
        },
      },
      {
        label: '启停状态',
        prop: 'startStopStatus',
        type: 'radio',
        option: [
          { value: '0', label: '启用' },
          { value: '1', label: '禁用' },
        ],
        span: 12,
        formatter: (row) => {
          return row === '0' ? '是' : '否';
        },
      }, //0启用 1禁用
      {
        label: '最近修改时间',
        prop: 'updateDate',
        type: 'text',
        span: 12,
        show: false,
      },
      {
        label: '分类列表',
        prop: 'classificationId',
        type: 'select',
        span: 12,
        option: computed(() => pageDictOption.categoryList),
        formatter: (row) => {
          const option = pageDictOption.categoryList.find(
            (item) => item.value == row
          );
          return option ? option.label : row;
        },
      },
      { label: '应用图标', prop: 'icon', type: 'slot', span: 24 },
    ],
    itemTypeList: [],
  },
  config: {},
  formRules: {
    serviceItemName: [
      { required: true, message: '请输入服务事项名称', trigger: 'blur' },
    ],
    serviceObject: [
      { required: true, message: '请选择服务对象', trigger: 'change' },
    ],
    responsibleDepartment: [
      { required: true, message: '请选择责任部门', trigger: 'change' },
    ],
    serviceTopic: [
      { required: true, message: '请输入服务主题', trigger: 'blur' },
    ],
    associationService: [
      { required: true, message: '请选择是否关联服务', trigger: 'blur' },
    ],
    startStopStatus: [
      { required: true, message: '请选择启停状态', trigger: 'blur' },
    ],
    updateDate: [{ required: true, message: '请选择状态', trigger: 'blur' }],
    classificationId: [
      { required: true, message: '请选择分类列表', trigger: 'change' },
    ],
    icon: [{ required: true, message: '请上传图标', trigger: 'change' }],
    file: [],
  },
  type: 'view', //edit // view
});
const upload = ref<any>(null);

onMounted(() => {
  // fnGetissuesList();
  // getAppTypeOptions();
  // fnGetDict();
});

const fnGetDict = () => {
  dictListApi({
    dictEnable: true,
    dictType: '服务对象',
    pageNo: 1,
    pageSize: 9999,
  }).then((res) => {
    pageDictOption.serveObject = res?.data.rows.map((r) => {
      return {
        value: r.dictValue,
        label: r.dictLabel,
      };
    });
  });

  getCategoryList().then((res) => {
    pageDictOption.categoryList = getOneArr(
      res?.data.map((r) => {
        return {
          value: r.id,
          label: r.name,
        };
      })
    );
  });

  //自定义字段
  getOptionList().then((res) => {
    pageDictOption.customField = res?.data.rows.map((r) => {
      dialogOption.formRules[r.fieldTag] = JSON.parse(r.validationRules);
      return { prop: r.fieldTag, label: r.fieldName, type: r.fieldType };
    });
    dialogOption.formOption.item.push(...pageDictOption.customField);
  });
};
async function getAppTypeOptions() {
  const { result, data } = await organizationList({
    pageNo: 1,
    pageSize: 99999,
  });

  // 判断result是否为true
  if (result) {
    appTypeOptions.value = data.rows
      .map((r) => {
        if (r.id) {
          return {
            value: r.id,
            label: r.organizationTitle,
          };
        }
      })
      .filter((l) => l != undefined);
  }
}
//查询列表
const fnGetissuesList = () => {
  tableData.value.loading = true;
  getissuesList({
    ...inlineForm.value.formData,
    ...tableData.value.pagination,
  })
    .then((res: any) => {
      tableData.value.data = res?.data.rows;
      tableData.value.pagination.total = res?.data.total;
    })
    .finally(() => {
      tableData.value.loading = false;
    });
};
const fnInlinFormBtnClick = (data: any, type: string) => {
  if (type === 'search') {
    fnGetissuesList();
  } else {
    fnGetissuesList();
  }
}; //新建
const fnBtnClick = (data) => {
  switch (data.name) {
    case 'accessApp':
      dialogOption.type = 'add';
      dialogOption.title = '新建服务事项';
      dialogOption.file = [];
      if (dialogOption.formOption.itemTypeList) {
        dialogOption.formOption.itemTypeList.forEach((item, index) => {
          dialogOption.formOption.item[index].type = item;
        });
      }
      dialogOption.formOption.item[6].show = false;
      dialogOption.formData = {};
      dialogRef.value?.open();
      break;
  }
};

//查看详情
const fnHandleView = (row: any) => {
  dialogOption.formOption.item.forEach((item, index) => {
    dialogOption.formOption.itemTypeList.push(item.type);
    dialogOption.formOption.item[index].type = 'text';
  });

  dialogOption.title = '查看服务事项';
  dialogOption.type = 'view';
  dialogOption.formOption.item[6].show = true;
  dialogRef.value?.open();
  getIssuesDetail(row.id).then((res: any) => {
    dialogOption.formData = res?.data;
    let remark = JSON.parse(dialogOption.formData.remark);
    dialogOption.formData = { ...dialogOption.formData, ...remark };
  });
};

//启停状态切换
const fnStartAndStop = (row: any, type: Boolean) => {
  let newObj = { ...row }; // 展开运算符浅拷贝

  let message = '';

  if (type) {
    message = '禁用成功';
    newObj.startStopStatus = '1';
  } else {
    message = '启用成功';
    newObj.startStopStatus = '0';
  }
  tableData.value.loading = true;
  editIssues(newObj).then((res: any) => {
    if (res.code === 200) {
      ElMessage({
        type: 'success',
        message: message,
      });
      fnGetissuesList({});
    } else {
      ElMessage({
        type: 'info',
        message: res.msg,
      });
    }
  });
};

//删除
const fnHandleDelete = (row: any) => {
  ElMessageBox.confirm('删除后将无法恢复，确认要删除吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'error',
  }).then(() => {
    deletIssues([row.id]).then((res: any) => {
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        });
        fnGetissuesList({});
      } else {
        ElMessage({
          type: 'info',
          message: res.msg,
        });
      }
    });
  });
};

//翻页
const fnHandlePageChange = (pageData: any) => {
  tableData.value.pagination.pageNumber = pageData.page;
  tableData.value.pagination.pageSize = pageData.limit;
  fnGetissuesList();
};

//保存弹窗
const fnSaveDialong = async () => {
  if (dialogOption.type === 'add') {
    dialogRefForm.value.validate((valid: boolean) => {
      if (!valid) return;
      let newObj = {};
      pageDictOption.customField.forEach((item) => {
        newObj[item.prop] = dialogOption.formData[item.prop];
        dialogOption.formData[item.prop] = null;
      });

      dialogOption.formData.remark = JSON.stringify(newObj);
      createIssues(dialogOption.formData).then((res: any) => {
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '新建成功',
          });
          dialogRef.value?.close(true);
          fnGetissuesList({});
        } else {
          ElMessage({
            type: 'error',
            message: res.msg,
          });
        }
      });
    });
  }
};

const fnHandleExceed = (files) => {
  upload.value!.clearFiles();
  const file = files[0];
  upload.value!.handleStart(file);
};

const fnUpload = async (file) => {
  let data = {};
  data.file = file.raw;
  uploadingFile(data).then((res) => {
    if (res.code === 200) {
      const url = res.data;

      dialogOption.formData.icon = baseUrl + url;
    } else {
      ElMessage({
        type: 'error',
        message: res.msg,
      });
    }
  });
};
</script>

<template>
  <div class="app-container">
    <xt-inlin-form
      v-model="inlineForm.formData"
      :items="inlineForm.items"
      :bars="inlineForm.bars"
      @fun="fnInlinFormBtnClick">
    </xt-inlin-form>
    <!-- <xt-table
      v-loading="tableData.loading"
      :topBtn="tableData.topBtn"
      :data="tableData.data"
      :columns="tableData.columns"
      @pagination-change="fnHandlePageChange"
      @btnClick="fnBtnClick"
      :pagination="true"
      :layout="['total', 'prev', 'pager', 'next', 'sizes']"
      :total="tableData.pagination.total"
      :headerRowStyle="{
        backgroundColor: '##03EFF3F7',
      }">
      <template #operate="scpoed">
        <el-link type="primary" @click="fnHandleView(scpoed.row)">查看</el-link>

        <el-link
          class="ml20"
          type="primary"
          @click="
            fnStartAndStop(scpoed.row, scpoed.row.startStopStatus === '0')
          ">
          {{ scpoed.row.startStopStatus === '1' ? '启用' : '停用' }}
        </el-link>
        <el-link
          type="primary"
          @click="fnHandleDelete(scpoed.row)"
          class="ml20">
          删除
        </el-link>
      </template>
    </xt-table> -->
    <!-- <xt-dialog ref="dialogRef" :title="dialogOption.title"> -->
    <div style="padding: 45px 100px 0">
      <xt-form
        v-model="dialogOption.formData"
        :items="dialogOption.formOption.item"
        :config="dialogOption.config"
        :rules="dialogOption.formRules"
        labelWidth="120px">
      </xt-form>
    </div>

    <!-- <template #footer>
        <div class="fct">
          <el-button @click="dialogRef.close(true)"> 取消 </el-button>
          <el-button
            @click="fnSaveDialong"
            v-if="dialogOption.type != 'view'"
            type="primary">
            保存
          </el-button>
        </div>
      </template> -->
    <!-- </xt-dialog> -->
  </div>
</template>
<style>
.app-container {
  padding: 20px;
}
</style>
